<template>
  <view class="fixed" :class="[`fixed--${position}`]">
    <view class="fixed__container" :style="[getContainerStyle]">
      <view class="fixed__content">
        <slot />
        <m-safe-bottom v-if="position === 'bottom'" />
      </view>
    </view>
    <view class="fixed__placeholder" :style="[{ height: height + 'px' }]" />
  </view>
</template>

<script lang="ts">
import getCurrentComponent from '@/utils/get-current-component'
import { defineComponent, onMounted, reactive, toRefs, computed } from '@vue/composition-api'
import boundingClientRect from '@/utils/bounding-client-rect'
import addUnit from '@/utils/add-unit'
import addColor from '@/utils/add-color'

export default defineComponent({
  props: {
    position: {
      type: String,
      default: 'bottom',
    },
    bottom: {
      type: [Number, String],
      default: 0,
    },
    background: {
      type: String,
      default: '#fff',
    },
    padding: {
      type: String,
      default: `12rpx 24rpx`,
    },
    showBorder: {
      type: Boolean,
      default: false,
    },
  },
  setup(props) {
    const vm = getCurrentComponent()
    const state = reactive({
      height: 0,
    })
    const getContainerStyle = computed(() => {
      return {
        padding: props.padding,
        bottom: addUnit(props.bottom),
        background: addColor(props.background),
        border: props.showBorder ? '1rpx solid #eee' : '',
      }
    })

    onMounted(async () => {
      // app端onMounted 页面还没有好 取值高度取不到 用setTimeout
      setTimeout(async () => {
        const rect: any = await boundingClientRect('.fixed__container', vm)
        state.height = rect.height
      }, 50)
    })

    return {
      ...toRefs(state),
      getContainerStyle,
    }
  },
})
</script>
<style lang="scss" scoped>
.fixed {
  &__container {
    position: fixed;
    left: 0;
    right: 0;
    z-index: 11;
    box-shadow: 0px 0px 13px 0px rgba(200, 208, 217, 0.42);
  }

  &--bottom {
    .fixed__container {
      bottom: 0;
    }
  }

  &--top {
    .fixed__container {
      top: 0;
    }
  }
}
</style>
